import BaseComponent from "http://component.119safe.cn/component/base.js";

new class Paging extends BaseComponent
{
	/*
	 * records		记录总数
	 * pages		总页数
	 * current		当前页码(首页为1)
	 * page_changed	页码有效变动事件函数名
	 */
	Properties = { "records": 0, "pages": 0, "current": 0, "page_changed": ""};

	render() { super.render(this.constructor.name); }

	postRender(replacing)
	{
		let btn = $(replacing).find("button");
		btn[0].onclick = this.first;
		btn[1].onclick = this.prev;
		btn[2].onclick = this.next;
		btn[3].onclick = this.last;
	}


	Content = `
<div page="{current}" pages="{pages}" changed="{page_changed}">
	<button class="btn btn-info btn-sm"><i class="fa fa-fast-backward"></i></button>
	<button class="btn btn-info btn-sm"><i class="fa fa-backward"></i></button>
	<span current>{current}</span> / {pages}页，{records}条
	<button class="btn btn-info btn-sm"><i class="fa fa-forward"></i></button>
	<button class="btn btn-info btn-sm"><i class="fa fa-fast-forward"></i></button>
</div>
`;

	first()
	{
		let ctl = $(event.target).parents("div[page]"), busy = ctl.attr("busy")?.length > 0, page = parseInt(ctl.attr("page")), changed = ctl.attr("changed");

		if (busy) return; else ctl.attr("busy", "a");

		if (page == 1)
		{
			ctl.removeAttr("busy");
			alert("当前已是首页");
			return;
		}

		ctl.attr("page", 1);
		$("span[current]").html(1);
		if(changed.length > 0) eval(`${changed}(${page = 1})`);
		ctl.removeAttr("busy");
	}

	prev()
	{
		let ctl = $(event.target).parents("div[page]"), busy = ctl.attr("busy")?.length > 0, page = parseInt(ctl.attr("page")), changed = ctl.attr("changed");

		if (busy) return; else ctl.attr("busy", "a");

		if (page == 1)
		{
			ctl.removeAttr("busy");
			alert("当前已是首页");
			return;
		}

		ctl.attr("page", --page);
		$("span[current]").html(page);
		if(changed.length > 0) eval(`${changed}(${page})`);
		ctl.removeAttr("busy");
	}

	next()
	{
		let ctl = $(event.target).parents("div[page]"), busy = ctl.attr("busy")?.length > 0, page = parseInt(ctl.attr("page")), pages = parseInt(ctl.attr("pages")), changed = ctl.attr("changed");

		if (busy) return; else ctl.attr("busy", "a");

		if (page >= pages)
		{
			ctl.removeAttr("busy");
			alert("当前已是尾页");
			return;
		}

		ctl.attr("page", ++page);
		$("span[current]").html(page);
		if(changed.length > 0) eval(`${changed}(${page})`);
		ctl.removeAttr("busy");
	}

	last()
	{
		let ctl = $(event.target).parents("div[page]"), busy = ctl.attr("busy")?.length > 0, page = parseInt(ctl.attr("page")), pages = parseInt(ctl.attr("pages")), changed = ctl.attr("changed");

		if (busy) return; else ctl.attr("busy", "a");

		if (page >= pages)
		{
			ctl.removeAttr("busy");
			alert("当前已是尾页");
			return;
		}

		ctl.attr("page", pages);
		$("span[current]").html(pages);
		if(changed.length > 0) eval(`${changed}(${pages})`);
		ctl.removeAttr("busy");
	}
}().render();
